<template>
  <div class="app-container" style="height: 100%">
    <div
      class="app-container-inner"
      style="display: flex; flex-direction: column; flex: 1"
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <div class="header">
        <div class="btns-left">
          <HPlainButton @click="addData">新增客户</HPlainButton>
          <HPlainButton @click="onImportUser">导入</HPlainButton>
          <HPlainButton @click="onExportUser">导出</HPlainButton>
          <el-dropdown trigger="click">
            <HButton :disabled="selecttion.length === 0">
              批量操作
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </HButton>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="changeAll(1)">
                  <el-icon>
                    <CircleCheck />
                  </el-icon>
                  批量启用
                </el-dropdown-item>
                <el-dropdown-item @click="changeAll(2)">
                  <el-icon>
                    <Warning />
                  </el-icon>
                  批量禁用
                </el-dropdown-item>
                <el-dropdown-item @click="changeAll(3)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  批量删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="search flex-align-center">
          <el-select
            v-model="userListSearch.status"
            class="input-width mr5"
            placeholder="客户状态"
            filterable
            clearable
            reserve-keyword
            remote-show-suffix
            :loading="levelLoading"
            :filter-method="searchLevelSelect"
            @change="getList"
          >
            <el-option
              v-for="item in userStatus"
              :key="item.status"
              :label="item.name"
              :value="item.status"
            />
          </el-select>
          <el-select
            v-model="userListSearch.levelId"
            class="input-width mr5"
            placeholder="客户级别"
            filterable
            clearable
            reserve-keyword
            remote-show-suffix
            :loading="levelLoading"
            :filter-method="searchLevelSelect"
            @change="getList"
          >
            <el-option
              v-for="item in levelOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-select
            v-model="userListSearch.userTypeId"
            class="input-width mr5"
            placeholder="客户分类"
            filterable
            clearable
            reserve-keyword
            remote-show-suffix
            :loading="typeLoading"
            :filter-method="searchTypeSelect"
            @change="getList"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-input
            v-model="userListSearch.userSearch"
            placeholder="客户编码/账号昵称/账号"
            class="input-width mr5 userSearch"
            @keyup.enter="getList"
            @clear="getList"
            clearable
          />
          <el-input
            v-model="userListSearch.userContactSearch"
            placeholder="联系人姓名/手机号"
            class="input-width mr5 userSearch"
            @keyup.enter="getList"
            @clear="getList"
            clearable
          />
          <div class="btn_group">
            <HButton type="primary" @click="getList">
              <el-icon>
                <Search />
              </el-icon>
              搜索
            </HButton>
            <HButton @click="clearVlaue">
              <el-icon>
                <RefreshRight />
              </el-icon>
              重置
            </HButton>
          </div>
        </div>
      </div>
      <div class="table">
        <el-table
          border
          stripe
          resizable
          :data="userList"
          @cell-dblclick="gouserDetail"
          @selection-change="handleChange"
          ref="tableDom"
          height="100%"
          style="position: absolute"
        >
          <el-table-column type="selection" width="40" fixed />

          <!-- 序号 -->
          <el-table-column type="index" label="序号" width="50" fixed align="center" />

          <!-- 绑定账号 -->
          <el-table-column show-overflow-tooltip prop="account" label="绑定账号" width="104" fixed>
            <template #default="scope">
              <HLink @click="gouserDetail(scope.row)">{{ scope.row.account }}</HLink>
            </template>
          </el-table-column>

          <!-- 帐号昵称 -->
          <el-table-column
            show-overflow-tooltip
            prop="accountName"
            label="账号昵称"
            width="130"
            fixed
          />

          <!-- 客户识别码 -->
          <el-table-column show-overflow-tooltip prop="code" label="客户识别码" width="160" />

          <!-- 状态 -->
          <el-table-column show-overflow-tooltip prop="status" label="状态" width="70">
            <template #default="scope">
              <HStatus
                v-for="item in userStatus"
                :key="item.status"
                v-show="scope.row.status == item.status"
                :type="item.status == 0 ? 'primary' : item.status == 1 ? 'success' : 'info'"
                >{{ item.name }}</HStatus
              >
            </template>
          </el-table-column>

          <!-- 主联系人 -->
          <el-table-column show-overflow-tooltip prop="username" label="主联系人" width="130" />

          <!-- 主联系人手机号 -->
          <el-table-column show-overflow-tooltip prop="phone" label="主联系人手机号" width="110" />

          <!-- 客户分类 -->
          <el-table-column show-overflow-tooltip prop="userType" label="客户分类" width="100" />

          <!-- 关联商家 -->
          <el-table-column
            show-overflow-tooltip
            prop="selectKnowledgeAuthor"
            label="关联商家"
            width="134"
          >
            <template #default="scope">
              <span>{{ scope.row.factoryList.join(' ') }}</span>
            </template>
          </el-table-column>

          <!-- 客户等级 -->
          <el-table-column show-overflow-tooltip prop="level" label="客户等级" width="100" />

          <!-- 关联工单量 -->
          <el-table-column prop="orderNo" label="关联工单量" width="85" align="center" />

          <!-- 关联产品书 -->
          <el-table-column prop="productNo" label="关联产品数" width="85" align="center" />

          <!-- 绑定微信 -->
          <el-table-column prop="bindingWechat" label="绑定微信" width="74">
            <template>
              <span>暂未绑定</span>
            </template>
          </el-table-column>

          <!-- 注册时间 -->
          <el-table-column show-overflow-tooltip prop="createTime" label="注册时间" width="128" />

          <!-- 更新时间 -->
          <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="128" />
        </el-table>
      </div>
      <div class="footer">
        <Pagination
          ref="paginDom"
          :list_total="total"
          @size-change="getList"
          @current-change="getList"
        />
      </div>

      <!-- 新增客户弹窗 -->
      <HModal v-model="addDialog" title="新增客户" :width="550">
        <template #header>
          <div class="my-header">
            <h3 class="title">{{ userForm.title }}</h3>
          </div>
        </template>
        <div v-loading="addLoading" element-loading-text="加载中...">
          <el-form
            label-width="80px"
            ref="userFormRef"
            :model="userForm"
            :rules="rules"
            @validate="handleAddCustomerFormValidate"
          >
            <div class="add_customer_modal_form_content">
              <!-- 客户名称 -->
              <el-form-item
                label="客户名称"
                prop="name"
                :class="{
                  validate_fail: !addCustomerFormValidateResult['name'],
                  form_item: addCustomerFormValidateResult['name'],
                }"
              >
                <el-input
                  v-model="userForm.name"
                  placeholder="请输入客户名称"
                  class="input-width"
                  clearable
                />
              </el-form-item>

              <!-- 客户电话 -->
              <el-form-item
                label="客户电话"
                prop="phone"
                :class="{
                  validate_fail: !addCustomerFormValidateResult['phone'],
                  form_item: addCustomerFormValidateResult['phone'],
                }"
              >
                <el-input
                  v-model="userForm.phone"
                  placeholder="请输入客户手机号"
                  class="input-width"
                  clearable
                  maxlength="11"
                />
              </el-form-item>

              <!-- 客户级别 -->
              <el-form-item label="客户级别" class="form_item">
                <el-select
                  v-model="userForm.levelId"
                  class="input-width"
                  placeholder="客户级别"
                  filterable
                  clearable
                  reserve-keyword
                  remote-show-suffix
                  :loading="levelLoading"
                  :filter-method="searchLevelSelect"
                >
                  <el-option
                    v-for="item in levelOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>

              <!-- 客户分类 -->
              <el-form-item
                label="客户分类"
                prop="userTypeId"
                :class="{
                  validate_fail: !addCustomerFormValidateResult['userTypeId'],
                  form_item: addCustomerFormValidateResult['userTypeId'],
                }"
              >
                <el-select
                  v-model="userForm.userTypeId"
                  class="input-width mr5"
                  placeholder="客户分类"
                  filterable
                  clearable
                  reserve-keyword
                  remote-show-suffix
                  :loading="typeLoading"
                  :filter-method="searchTypeSelect"
                >
                  <el-option
                    v-for="item in typeOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>

              <!-- 客户地址 -->
              <el-form-item
                label="客户地址"
                prop="addrs"
                :class="{
                  validate_fail: !addCustomerFormValidateResult['addrs'],
                  form_item: addCustomerFormValidateResult['addrs'],
                }"
              >
                <SingleAddress ref="addrsDom" 
                :address="{
                  province: '',
                  city: '',
                  area: '',
                  town: '',
                  SelectType: false, // 默认多选
                }" @value-change="handleChangeCustomerAddrs" @clear="handleClear" />
              </el-form-item>

              <!-- 详细地址 -->
              <el-form-item
                label="详细地址"
                prop="address"
                :class="{
                  validate_fail: !addCustomerFormValidateResult['address'],
                  form_item: addCustomerFormValidateResult['address'],
                }"
              >
                <el-input
                  v-model="userForm.address"
                  placeholder="请输入详细地址"
                  class="input-width"
                  clearable
                />
              </el-form-item>

              <!-- 客户编码 -->
              <el-form-item label="客户编码" class="form_item">
                <el-input
                  v-model="userForm.code"
                  placeholder="如无编码系统自动生成"
                  class="input-width"
                  clearable
                />
              </el-form-item>

              <!-- 客户邮箱 -->
              <el-form-item label="客户邮箱" prop="email" class="form_item">
                <el-input
                  v-model="userForm.email"
                  placeholder="请输入邮箱"
                  class="input-width"
                  clearable
                />
              </el-form-item>

              <!-- 客户状态 -->
              <el-form-item label="客户状态" class="last_form_item">
                <div style="display: flex; align-items: center; gap: 5px">
                  <el-switch v-model="userForm.status" />
                  <span v-if="userForm.status">启用</span>
                  <span v-else>禁用</span>
                </div>
              </el-form-item>
            </div>
          </el-form>
        </div>

        <template #footerRight>
          <HButton is-modal @click="saveData(userFormRef)" type="primary">保存</HButton>
          <HButton is-modal @click="onAddCustomerModalCancelClick"> 取消 </HButton>
        </template>
      </HModal>
    </div>

    <!-- 客户导出弹窗 -->
    <HModal v-model="exportDialog" size="small">
      <template #header>
        <div class="my-header">
          <h3 class="title">客户数据导出</h3>
        </div>
      </template>
      <div class="export-form">
        <div class="export-title" style="margin-bottom: 12px">
          <span>客户数据总数量：</span>
          <span>{{ total }}</span>
        </div>

        <div class="export_modal_form_content">
          <!-- 客户状态 -->
          <el-select
            @change="getList"
            v-model="userListSearch.status"
            class="export-input-width"
            placeholder="客户状态"
            filterable
            clearable
            reserve-keyword
            remote-show-suffix
            :loading="levelLoading"
            :filter-method="searchLevelSelect"
          >
            <el-option
              v-for="item in userStatus"
              :key="item.status"
              :label="item.name"
              :value="item.status"
            />
          </el-select>

          <!-- 客户级别 -->
          <el-select
            @change="getList"
            v-model="userListSearch.levelId"
            class="export-input-width mr5"
            placeholder="客户级别"
            filterable
            clearable
            reserve-keyword
            remote-show-suffix
            :loading="levelLoading"
            :filter-method="searchLevelSelect"
          >
            <el-option
              v-for="item in levelOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>

          <!-- 客户分类 -->
          <el-select
            @change="getList"
            v-model="userListSearch.userTypeId"
            class="export-input-width"
            placeholder="客户分类"
            filterable
            clearable
            reserve-keyword
            remote-show-suffix
            :loading="typeLoading"
            :filter-method="searchTypeSelect"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>

          <el-input
            v-model="userListSearch.userSearch"
            placeholder="客户编码/账号昵称/账号"
            class="export-input-width mr5"
            @keyup.enter="getList"
            @clear="getList"
            clearable
          />

          <el-input
            v-model="userListSearch.userContactSearch"
            placeholder="联系人姓名/手机号"
            class="export-input-width"
            @keyup.enter="getList"
            @clear="getList"
            clearable
          />

          <div class="btn_group">
            <HButton type="primary" @click="getList">
              <el-icon>
                <Search />
              </el-icon>
              搜索
            </HButton>
            <HButton @click="clearVlaue">
              <el-icon>
                <RefreshRight />
              </el-icon>
              重置
            </HButton>
          </div>
        </div>
      </div>

      <template #footerRight>
        <HButton is-modal type="primary" @click="onExportUserData" :loading="exportLoading"
          >导出</HButton
        >
        <HButton is-modal @click="exportDialog = false">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch, markRaw } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormItemProp } from 'element-plus'
  import { useRoute, useRouter } from 'vue-router'
  import {
    Search,
    Delete,
    Warning,
    ArrowDown,
    CircleCheck,
    RefreshRight,
  } from '@element-plus/icons-vue'
  import moment from 'moment'
  import Pagination from '@/components/Pagination/index.vue'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import { phone } from '@/utils/validate'
  import {
    getUsersList,
    levelPageSelect,
    typePageSelect,
    addUser,
    changeStatus,
    deleteUser,
    userExportExcel,
  } from '@/api/users'
  import { User } from './types'
  import _ from 'lodash'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.customer.customerList,
  })

  // 激活的路由对象
  const route = useRoute()

  // 全局路由对象
  const router = useRouter()
  const addDialog = ref(false)
  const loading = ref(false)
  const exportDialog = ref(false) // 客户数据导出弹窗
  const exportLoading = ref(false) // 客户数据导出弹窗加载动画

  // 搜索框
  const levelId = ref('') // 客户级别ID
  const typeId = ref('') // 客户分类ID

  // 下拉数据
  const levelOptions = ref([]) // 级别
  const typeOptions = ref([]) // 分类

  const levelVal = ref('')
  const levelLoading = ref(false)

  const typeVal = ref('')
  const typeLoading = ref(false)

  const userList = ref<Array<User>>([]) // 列表数据
  const tableDom = ref() // 列表dom
  const userStatus = ref([
    // 客户状态
    { status: 0, name: '启用' },
    { status: 1, name: '冻结' },
    { status: 2, name: '禁用' },
  ])

  // 分页数据
  const paginDom = ref() // 分页dom
  const total = ref() // 总数目
  const userListSearch = ref({
    // 客户列表搜索条件
    page: 1,
    limit: 50,
    status: '', // 用户状态：0-正常，1-冻结，2-禁用
    levelId: '', // 用户级别ID
    userTypeId: '', // 用户分类ID
    userSearch: '', // 账号关键词搜索
    userContactSearch: '', // 联系人搜索关键词
  })

  // 客户表单数据
  const userForm = reactive({
    addrs: null,
    address: '',
    code: '',
    email: '',
    id: null,
    level: '',
    levelId: '',
    name: '',
    phone: '',
    status: true,
    title: '',
    userType: '',
    userTypeId: '',
    selectKnowledgeAuthor: false,
  })

  // 验证规则
  const rules = reactive({
    address: [{ required: true, message: '请输入详细地址', trigger: ['change', 'blur'] }],
    name: [{ required: true, message: '请输入客户名称', trigger: ['change', 'blur'] }],
    phone: [
      { required: true, message: '请输入手机号', trigger: ['change', 'blur'] },
      { validator: phone(userForm.phone), trigger: ['change', 'blur'] },
    ],
    addrs: [
      { required: true, message: '请选择客户地址', trigger: ['change', 'blur'] },
      {
        validator: (rule, value, callback) => {
          console.log('userForm.addrs.province', userForm.addrs.province)
          if (!userForm.addrs || !userForm.addrs.province) {
            callback(new Error('请选择客户地址'))
          } else {
            callback()
          }
        },
        trigger: ['change', 'blur'],
      },
    ],
    levelId: [{ required: true, message: '请选择客户级别', trigger: 'change' }],
    userTypeId: [{ required: true, message: '请选择客户分类', trigger: 'change' }],
    email: [
      { required: false, message: '请输入邮箱', trigger: 'change' },
      {
        pattern:
          /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
        message: '邮箱格式不正确',
        trigger: 'change',
      },
    ],
  })

  const addrsDom = ref()
  const addLoading = ref(false)
  const userFormRef = ref<FormInstance>()

  // 获取分页下拉数据
  const getPageData = (name) => {
    return {
      limit: 0,
      name: name,
      page: 0,
    }
  }

  // 获取级别下拉
  const getLevelOptions = (name) => {
    levelPageSelect(getPageData(name)).then((res) => {
      levelOptions.value = res.data.data.rows
    })
  }

  // 搜索级别下拉数据
  const searchLevelSelect = _.throttle((query: string) => {
    levelVal.value = query
    if (query) {
      levelLoading.value = true
      setTimeout(async () => {
        levelLoading.value = false
      }, 1000)
    }
  }, 500)

  // 获取分类下拉
  const getTypeOptions = (name) => {
    typePageSelect(getPageData(name)).then((res) => {
      typeOptions.value = res.data.data.rows
    })
  }

  // 搜索分类下拉数据
  const searchTypeSelect = _.throttle((query: string) => {
    typeVal.value = query
    if (query) {
      typeLoading.value = true
      setTimeout(async () => {
        typeLoading.value = false
      }, 1000)
    }
  }, 500)

  // 监听下拉数据变化时是否进行搜索
  watch(
    () => levelVal.value,
    (newVal) => {
      if (newVal != '') {
        getLevelOptions(newVal)
      } else {
        getLevelOptions('')
      }
    },
  )
  watch(
    () => typeVal.value,
    (newVal) => {
      if (newVal != '') {
        getTypeOptions(newVal)
      } else {
        getTypeOptions('')
      }
    },
  )

  // 重置搜索
  const clearVlaue = () => {
    userListSearch.value = {
      page: 1,
      limit: 50,
      status: '', // 用户状态：0-正常，1-冻结，2-禁用
      levelId: '', // 用户级别ID
      userTypeId: '', // 用户分类ID
      userSearch: '', // 账号关键词搜索
      userContactSearch: '', // 联系人搜索关键词
    }
    getList()
  }

  // 获取列表数据
  const getList = async () => {
    userListSearch.value.page = paginDom.value.current
    userListSearch.value.limit = paginDom.value.size
    loading.value = true
    const res = await getUsersList(userListSearch.value)
    loading.value = false
    userList.value = res.data.data.rows
    total.value = parseInt(res.data.data.total)
  }

  onMounted(() => {
    getList()
    getLevelOptions(levelId.value)
    getTypeOptions(typeId.value)
  })

  // 导入
  const onImportUser = () => {
    router.push({ path: 'userExcelImport' })
  }
  // 导出窗口
  const onExportUser = () => {
    exportDialog.value = true
  }

  // 导出客户数据
  const onExportUserData = () => {
    exportLoading.value = true
    userExportExcel(userListSearch.value).then((res) => {
      exportLoading.value = false
      if (res.data.isError)
        ElMessage({
          type: res.data.code && !res.data.success ? 'error' : 'success',
          message: res.data.code && !res.data.success ? res.data.message : '客户数据导出成功',
        })
      if (res.data.code && !res.data.success) {
        return
      }
      const url = window.URL.createObjectURL(new Blob([res.data], { type: '.xlsx' }))
      const link = document.createElement('a')
      link.href = url
      link.download = `客户档案_${moment(new Date()).format('YYYYMMDD')}.xlsx`
      link.click()
      exportDialog.value = false
    })
  }

  // 新增客户
  const addData = () => {
    userForm.title = '新增客户'
    userForm.name = ''
    userForm.phone = ''
    userForm.levelId = ''
    userForm.userTypeId = ''
    userForm.address = ''
    userForm.code = ''
    userForm.email = ''
    userForm.status = true
    addDialog.value = true
  }

  // 保存数据
  const saveData = (formEl: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        saveMethod()
      }
    })
  }

  // 保存的方法
  const saveMethod = () => {
    const addr = addrsDom.value.getSelectAddr()
    console.log('addr============>>', addr)
    if (userForm.levelId) {
      levelOptions.value.forEach((item) => {
        if (userForm.levelId == item.id) {
          userForm.level = item.name
        }
      })
    }
    if (userForm.userTypeId) {
      typeOptions.value.forEach((item) => {
        if (userForm.userTypeId == item.id) {
          userForm.userType = item.name
        }
      })
    }
    const data = {
      code: userForm.code,
      email: userForm.email,
      id: userForm.id,
      level: userForm.level,
      levelId: userForm.levelId,
      name: userForm.name,
      phone: userForm.phone,
      status: userForm.status ? 0 : 2,
      province: addr.province,
      city: addr.city,
      area: addr.area,
      town: addr.town,
      address: userForm.address,
      userType: userForm.userType,
      userTypeId: userForm.userTypeId,
    }
    addLoading.value = true
    addUser(data).then((res) => {
      addLoading.value = false
      if (res.data.isError)
        ElMessage({
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
          duration: 2000,
        })
      if (res.data.success) {
        addDialog.value = false
        getList()
      }
    })
  }

  // 查看客户详情
  const gouserDetail = (obj) => {
    router.push({ path: 'userdetail/' + obj.id })
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: any[]) => {
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 封装修改状态的方法
  const changeDisable = (type, name, method, arr, status, dom, getList) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的${name}`,
        type: 'warning',
        duration: 2000,
      })
      return
    }
    ElMessageBox({
      type: type == '删除' ? 'error' : 'warning',
      title: '提示',
      icon: type == '删除' ? markRaw(Delete) : markRaw(Warning),
      message: `确认${type}选中的${name}?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != '3') {
        await method(arr, status).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
        })
      } else {
        await method(arr).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
        })
      }
      selecttion.value = []
      dom.clearSelection()
      getList()
    })
  }

  // 批量启用/禁用/删除
  const changeAll = (n) => {
    if (n == 1) {
      changeDisable('启用', '客户', changeStatus, selecttion.value, '0', tableDom.value, getList)
    }
    if (n == 2) {
      changeDisable('禁用', '客户', changeStatus, selecttion.value, '2', tableDom.value, getList)
    }
    if (n == 3) {
      changeDisable('删除', '客户', deleteUser, selecttion.value, '3', tableDom.value, getList)
    }
  }

  const addCustomerFormValidateResult = ref({
    name: true,
    phone: true,
    userTypeId: true,
    address: true,
    addrs: true,
  })

  const handleAddCustomerFormValidate = (prop: FormItemProp, isValid: boolean) => {
    addCustomerFormValidateResult.value[prop as string] = isValid
  }

  const onAddCustomerModalCancelClick = () => {
    addDialog.value = false
    addCustomerFormValidateResult.value = {
      name: true,
      phone: true,
      userTypeId: true,
      address: true,
      addrs: true,
    }
  }

  const handleChangeCustomerAddrs = () => {
    if (addrsDom.value) {
      userForm.addrs = addrsDom.value.getSelectAddr()
    }
  }

  const handleClear = () => {
    userForm.addrs = {}
  }

  watch(
    () => route.name,
    (value) => {
      if (value === 'Userlist') {
        getList()
        getLevelOptions(levelId.value)
        getTypeOptions(typeId.value)
      }
    },
  )
</script>

<style scoped lang="scss">
  @import './index';
</style>
